#include "RTSPStream.h"

RTSPStream::RTSPStream(const std::string& url) : rtspUrl(url), formatCtx(nullptr), videoStreamIndex(-1) {}

RTSPStream::~RTSPStream() {
    close();
}

bool RTSPStream::open() {
    // 初始化FFmpeg网络组件
    avformat_network_init();

    // 分配AVFormatContext结构体
    formatCtx = avformat_alloc_context();

    // 创建并设置AVDictionary选项
    AVDictionary* iformat_opts = nullptr;
    av_dict_set(&iformat_opts, "buffer_size", "4096000", 0);
    av_dict_set(&iformat_opts, "rtsp_transport", "tcp", 0);
    av_dict_set(&iformat_opts, "stimeout", "5000000", 0);
    av_dict_set(&iformat_opts, "max_delay", "500000", 0);

    // 打开输入流
    if (avformat_open_input(&formatCtx, rtspUrl.c_str(), nullptr, &iformat_opts) != 0) {
        std::cerr << "avformat_open_input err" << std::endl;
        av_dict_free(&iformat_opts); // 释放字典
        return false;
    }

    av_dict_free(&iformat_opts); // 释放字典

    // 查找流信息
    if (avformat_find_stream_info(formatCtx, nullptr) < 0) {
        std::cerr << "avformat_find_stream_info err" << std::endl;
        return false;
    }

    // 查找视频流索引
    for (int i = 0; i < formatCtx->nb_streams; i++) {
        if (formatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoStreamIndex = i;
            break;
        }
    }
    AVCodecParameters* codecpar = formatCtx->streams[videoStreamIndex]->codecpar;
    AVCodecID codec_id = codecpar->codec_id;
    const char* codec_name = avcodec_get_name(codec_id);
    mCodeType = std::string(codec_name);
    std::cout << "Video codec: " << codec_name << std::endl;

    // 检查是否找到视频流
    if (videoStreamIndex == -1) {
        std::cerr << "videoStreamIndex err " << std::endl;
        return false;
    }

    return true;
}

void RTSPStream::close() {
    if (formatCtx) {
        avformat_close_input(&formatCtx);
        formatCtx = nullptr;
    }
}

bool RTSPStream::readFrame(AVPacket* packet) {
    while (av_read_frame(formatCtx, packet) >= 0) {
        if (packet->stream_index == videoStreamIndex) {
            return true;
        }
        av_packet_unref(packet);
    }
    return false;
}
